﻿using BaseFramework.DbConnectionProvider;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteFramework.Server.Component
{
    internal class InternalHelper
    {
        internal static bool ValidateUser(IDbConnectionProvider provider, string userName, string pwd, out string err)
        {
            err = null;

            var param = provider.CreateParameter("UserName", userName);
            string sql = string.Format("SELECT PasswordSalt FROM SYS_User WHERE UserName={0}", param.ParameterName);
            var salt = provider.ExecScalar(sql, param);
            if (salt == DBNull.Value)
            {
                err = "用户名不存在";
                return false;
            }

            var hashPwd = HashPwd(pwd, salt.ToString());
            var param1 = provider.CreateParameter("UserName", userName);
            var param2 = provider.CreateParameter("Password", hashPwd);
            sql = string.Format("SELECT COUNT(1) FROM SYS_User WHERE UserName={0} AND Password={1}", param1.ParameterName, param2.ParameterName);
            if ((int)provider.ExecScalar(sql, param1, param2) == 0)
            {
                err = "用户名或密码不正确";
                return false;
            }

            return true;
        }

        internal static string HashPwd(string pwd, string salt)
        {
            return LiteFramework.Security.MD5.CreateHash(pwd + "$" + salt);
        }
    }
}